package org.example.file;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8DuplicatedExample {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(5,3,4,1,3,7,2,9,9,4);
        //Set<Integer> result = findDuplicatedBySetAdd(list);
        //Set<Integer> result = findDuplicatedByGrouping(list);
        Set<Integer> result = findDuplicatedByFrequency(list);
        result.stream().forEachOrdered(System.err::println);
    }

    static <T> Set<T> findDuplicatedBySetAdd(List<T> list){
        Set<T> sets = new HashSet<>();
        return list.stream()
                .filter(n -> ! sets.add(n))
                .collect(Collectors.toSet());
    }

    static <T> Set<T> findDuplicatedByGrouping(List<T> list){
        Set<T> sets = new HashSet<>();
         sets = list.stream()
                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                 .entrySet()
                 .stream()
                 .filter(m -> m.getValue() > 1)
                 .map(Map.Entry::getKey)
                 .collect(Collectors.toSet());
         return sets;
    }

    static <T> Set<T> findDuplicatedByFrequency(List<T> list){
        return list.stream().filter(i -> Collections.frequency(list,i) > 1)
                .collect(Collectors.toSet());
    }
}
